package org.example;

import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory;
import org.apache.sshd.server.SshServer;
import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
import org.apache.sshd.sftp.server.SftpSubsystemFactory;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;

public class SFTPServer {

    public static void main(String[] args) {
        SshServer sshd = SshServer.setUpDefaultServer();
        sshd.setPort(2222);

        sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Paths.get("hostkey.ser")));

        // 设置密码验证器
        sshd.setPasswordAuthenticator((username, password, session) -> "your_password".equals(password));

        // 设置SFTP根目录和用户家目录
        VirtualFileSystemFactory virtualFileSystemFactory = new VirtualFileSystemFactory();
        virtualFileSystemFactory.setUserHomeDir("username", Paths.get("C:\\TEMP\\SFTP"));
        sshd.setFileSystemFactory(virtualFileSystemFactory);

        // 设置SFTP子系统
        sshd.setSubsystemFactories(Arrays.asList(new SftpSubsystemFactory()));

        try {
            sshd.start();
            System.out.println("SFTP服务器已启动...");
            new CountDownLatch(1).await();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
